package user

import (
	context "context"
	"encoding/json"

	"gitee.com/hexug/devcloud/mcenter/common/meta"
	"gitee.com/hexug/devcloud/mcenter/consted"
	"golang.org/x/crypto/bcrypt"
)

var (
	AppName = "users"
)

type Server interface {
	RPCServer
	// 删除用户
	DeleteUser(ctx context.Context, in *DeleteUserRequest) (*User, error)
}

func NewDeleteUserRequest() *DeleteUserRequest {
	return &DeleteUserRequest{
		DetailType: DESCRIBE_BY_USER_ID,
	}
}
func NewCreateUserRequest(username, password string) *CreateUserRequest {
	return &CreateUserRequest{
		Domain:   consted.DEFAULT_DOMAIN,
		Username: username,
		Password: password,
	}
}
func NewCreateUserRequestApi() *CreateUserRequest {
	return &CreateUserRequest{
		Domain: consted.DEFAULT_DOMAIN,
	}
}
func NewUser(in *CreateUserRequest) *User {
	return &User{
		Meta: meta.NewMeta(),
		Spec: in,
	}
}

func NewUserSet() *UserSet {
	return &UserSet{}
}
func NewUpdateUserRequest() *UpdateUserRequest {
	return &UpdateUserRequest{}
}

func NewQueryUserRequest() *QueryUserRequest {
	return &QueryUserRequest{
		PageSize:   5,
		PageNumber: 1,
	}
}

// 默认使用id
func NewDetailUserRequest() *DetailUserRequest {
	return &DetailUserRequest{
		DetailType: DESCRIBE_BY_USER_ID,
	}
}

// 使用id
func NewDetailUserRequestById(id string) *DetailUserRequest {
	return &DetailUserRequest{
		DetailType: DESCRIBE_BY_USER_ID,
		Value:      id,
	}
}

// 使用username
func NewDetailUserRequestByUsername(username string) *DetailUserRequest {
	return &DetailUserRequest{
		DetailType: DESCRIBE_BY_USERNAME,
		Value:      username,
	}
}

// 把对象自定义格式化
func (u *User) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		*meta.Meta
		*CreateUserRequest
	}{u.Meta, u.Spec})
}

// 结构体的方法
func (u *User) HashPassword() error {
	p1, err := bcrypt.GenerateFromPassword([]byte(u.Spec.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Spec.Password = string(p1)
	return nil
}

// 数据脱敏
func (u *User) Desensitize() {
	u.Spec.Password = "*****************"
}

// 单独的方法
func HashPassword(password string) (string, error) {
	p1, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}

	return string(p1), nil
}

// 检验密码
func (u *User) CheckPassword(passwd string) error {
	return bcrypt.CompareHashAndPassword([]byte(u.Spec.Password), []byte(passwd))
}
